package com.aqiang.lib_core.mvp

import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.jaeger.library.StatusBarUtil
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext

abstract class BaseActivity<P> : AppCompatActivity(),CoroutineScope {
    protected var mPresenter:P? = null
    private lateinit var job: Job
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(bindLatout())
        //沉浸式布局
        StatusBarUtil.setTranslucent(this)
        job = Job()
        createPresenter()
        initView(savedInstanceState)
        initData()
        initEvent()
    }

    protected fun doAsynTask(doSome:()->Unit){
        launch {
            withContext(Dispatchers.IO){
                doSome()
            }
        }
    }

    protected fun <T> doUiThread(r:Deferred<T>,doSome:(r:T)->Unit){
        GlobalScope.launch {
            withContext(Dispatchers.Main){
                doSome(r.await())
            }
        }
    }

    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

    abstract fun bindLatout(): Int

    abstract fun createPresenter()

    abstract fun initView(savedInstanceState: Bundle?)

    abstract fun initData()

    abstract fun initEvent()

    override fun onDestroy() {
        super.onDestroy()
        if(mPresenter != null){
            mPresenter = null
        }
        if(job != null){
            job.cancel()
        }
    }
}